//
//  CSSystemRouteNavigationService.swift
//  Cycling
//
//  Created by CSS on 4/15/23.
//

import Foundation
import MapboxCoreNavigation
import MapboxDirections
import Turf
import MapboxMaps
import MapboxNavigation

class CSSystemRouteNavigationService {
    public var navigationService: NavigationService!
    private var presentingVC: UIViewController?
    
    public var endNavigationBlock: (() -> Void)?
    
}

// MARK: 对外访问类(页面跳转)
extension CSSystemRouteNavigationService {
    
    class func showMapNavigation(withIndexRouteResponse indexRouteResponse: IndexedRouteResponse, presentingVC: UIViewController) -> CSSystemRouteNavigationService {
        
        let currentNavigationService: CSSystemRouteNavigationService = .init()
        currentNavigationService.presentingVC = presentingVC
        
        let navigationService = MapboxNavigationService(indexedRouteResponse: indexRouteResponse, credentials: NavigationSettings.shared.directions.credentials, simulating: .onPoorGPS)
        
        currentNavigationService.navigationService = navigationService
        let navigationOptions = NavigationOptions(navigationService: navigationService, voiceController: .init(navigationService: navigationService, speechSynthesizer: SystemSpeechSynthesizer()))
        let navigationVC = NavigationViewController(for: indexRouteResponse, navigationOptions: navigationOptions)
        navigationVC.delegate = currentNavigationService
        
        navigationVC.navigationMapView?.routeCasingColor = .color(withHexString: "#0FDAB2")
        navigationVC.navigationMapView?.trafficUnknownColor = .color(withHexString: "#0FDAB2")
        navigationVC.navigationMapView?.traversedRouteColor = .color(withHexString: "#808080")
        navigationVC.routeLineTracksTraversal = true
                
        navigationVC.modalPresentationStyle = .fullScreen
        presentingVC.present(navigationVC, animated: true)
        return currentNavigationService
    }
    
}

extension CSSystemRouteNavigationService: NavigationViewControllerDelegate {
    
    func navigationViewControllerDidDismiss(_ navigationViewController: NavigationViewController, byCanceling canceled: Bool) {
        presentingVC?.presentedViewController?.dismiss(animated: true) {
            self.endNavigationBlock?()
        }
    }
    
}
